package com.zhouyibike.uu.ui.activity.jvbaoandpaiming;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.PaiMingResult;
import com.zhouyibike.uu.entity.ZanResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.adapter.PaimingAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.TXCircleImageView;
import com.zhouyibike.uu.ui.view.timeselect.NumericWheelAdapter;
import com.zhouyibike.uu.ui.view.timeselect.OnWheelScrollListener;
import com.zhouyibike.uu.ui.view.timeselect.WheelView;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PaimingActivity extends BaseActivity implements View.OnClickListener{
    private ImageButton mBtnBack;
    private TextView mBtnTitle;

    private LinearLayout ll_nomsg,ll_hmsg,ll_selecttime;
    private TXCircleImageView txCircleImageView;
    private TextView tv_name,tv_pm,tv_mails,tv_zan,tv_time;
    private ImageView iv_xin;
    private PaimingAdapter paimingAdapter;
    private ListView lv_msg;
    private List<PaiMingResult.DataBean> list=new ArrayList<>();
    private boolean ismypress;
    private String myid;
    private String date="2017-05-22";
    private int zan;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paiming);
        initView();
        getMsg();
    }
    private void initView() {
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("骑行排名");
        mBtnBack.setOnClickListener(this);
        ll_nomsg= (LinearLayout) findViewById(R.id.ll_paiming_nomsg);
        ll_hmsg= (LinearLayout) findViewById(R.id.ll_paiming_hmsg);
        txCircleImageView= (TXCircleImageView) findViewById(R.id.txciv_paiming_myhead);
        tv_name= (TextView) findViewById(R.id.tv_paiming_name);
        tv_pm= (TextView) findViewById(R.id.tv_paiming_pm);
        tv_mails= (TextView) findViewById(R.id.tv_paiming_mails);
        tv_zan= (TextView) findViewById(R.id.tv_paiming_zans);
        iv_xin= (ImageView) findViewById(R.id.iv_paiming_xin);
        iv_xin.setOnClickListener(this);
        lv_msg= (ListView) findViewById(R.id.lv_paiming_allmsg);
        ll_selecttime= (LinearLayout) findViewById(R.id.ll_paiming_selecttime);
        ll_selecttime.setOnClickListener(this);
        date= TimeUtils.getCurrentTimeInStringpm();
        tv_time= (TextView) findViewById(R.id.tv_paiming_time);
        tv_time.setText(date);
    }
    private void getMsg(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("date", date);
        showProgressDialog();
        addSubscription(apiStores.RankingJourney(params),
                new ApiCallback<PaiMingResult>() {

                    @Override
                    public void onSuccess(PaiMingResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            if(model.getData().size()!=0){
                                ll_nomsg.setVisibility(View.GONE);
                                ll_hmsg.setVisibility(View.VISIBLE);
                                try {
                                    Picasso.with(PaimingActivity.this).load(preferences.getString("headPicture","")).networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE).into(txCircleImageView);
                                }catch (Exception e){

                                }
//                                txCircleImageView.setImageResource(model.getData().get(0).get);
                                myid=model.getData().get(0).getAccountId()+"";
                                tv_name.setText(model.getData().get(0).getName());
                                tv_pm.setText(model.getData().get(0).getIndex()+"");
                                tv_mails.setText(model.getData().get(0).getMileage()+"KM");
                                zan=model.getData().get(0).getPoints();
                                tv_zan.setText(model.getData().get(0).getPoints()+"");
                                if(model.getData().get(0).isHasPraised()){
                                    iv_xin.setImageResource(R.mipmap.zan_t);
                                    ismypress=true;
                                }else{
                                    iv_xin.setImageResource(R.mipmap.zan_f);
                                    ismypress=false;
                                }
                                list.addAll(model.getData());
//                                list.addAll(model.getData());
//                                list.addAll(model.getData());
                                initList();
                            }else{
                                ll_nomsg.setVisibility(View.VISIBLE);
                                ll_hmsg.setVisibility(View.GONE);
                            }
                        } else if (model.getStatus() == 508 || model.getStatus() == 506 || model.getStatus() == 307) {
                            setResult(2501);
                            finish();
                        } else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void initList(){
        paimingAdapter=new PaimingAdapter(this,list);
        lv_msg.setAdapter(paimingAdapter);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.iv_paiming_xin:
                if(ismypress){
                    break;
                }else{
                    mydianzan();
                }
                break;
            case R.id.ll_paiming_selecttime:
                initresultDailog();
                resultdialog.show();
                break;
        }
    }
    private Dialog resultdialog;
    private WheelView year;
    private WheelView month;
    private WheelView day;
    /**
     * 日期dialog
     */
    private void initresultDailog(){
        View view = LayoutInflater.from(this).inflate(
                R.layout.selecttime_dialog, null);
        resultdialog = new Dialog(this, R.style.loading_dialog);

        Calendar c = Calendar.getInstance();
        int curYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);

        year = (WheelView) view.findViewById(R.id.year);
        year.setAdapter(new NumericWheelAdapter(1950, curYear));
        year.setLabel("年");
        year.setCyclic(true);
        year.addScrollingListener(scrollListener);

        month = (WheelView) view.findViewById(R.id.month);
        month.setAdapter(new NumericWheelAdapter(1, 12));
        month.setLabel("月");
        month.setCyclic(true);
        month.addScrollingListener(scrollListener);

        day = (WheelView) view.findViewById(R.id.day);
        initDay(curYear,curMonth);
        day.setLabel("日");
        day.setCyclic(true);

        year.setCurrentItem(curYear - 1950);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate - 1);

        Button btn_sure= (Button) view.findViewById(R.id.btn_selecttime_sure);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                date=(year.getCurrentItem()+1950) + "-"+ (month.getCurrentItem()+1)+"-"+(day.getCurrentItem()+1);
                list.clear();
                tv_time.setText(date);
                getMsg();
                resultdialog.dismiss();
            }
        });

        ImageView iv_dismis= (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultdialog.dismiss();
            }
        });
        resultdialog.setContentView(view, new LinearLayout.LayoutParams(
                (int) (DataSingle.getInstance().PhoneW*0.8),
                LinearLayout.LayoutParams.WRAP_CONTENT));
        resultdialog.setCancelable(true);
        resultdialog.setCanceledOnTouchOutside(false);
        resultdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//
//        Window dialogWindow = resultdialog.getWindow();
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        dialogWindow.setGravity(Gravity.BOTTOM);
////                lp.x = 100; // 新位置X坐标
//        //  lp.y = DataSingle.getInstance().PhoneH; // 新位置Y坐标
//        // lp.width = DataSingle.getInstance().PhoneW; // 宽度
//        // lp.alpha = 0.7f; // 透明度
//        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
//        // dialog.onWindowAttributesChanged(lp);
//        dialogWindow.setAttributes(lp);
    }
    private void initDay(int arg1, int arg2) {
        day.setAdapter(new NumericWheelAdapter(1, getDay(arg1, arg2), "%02d"));
        if (day.getCurrentItem()-getDay(arg1, arg2)>=0)
        {
            day.setCurrentItem(getDay(arg1, arg2)-1);
        }else
        {
            day.setCurrentItem(day.getCurrentItem());
        }

    }
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }
    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {

        @Override
        public void onScrollingStarted(WheelView wheel) {

        }

        @Override
        public void onScrollingFinished(WheelView wheel) {
            // TODO Auto-generated method stub
            int n_year = year.getCurrentItem() + 1950;//
            int n_month = month.getCurrentItem() + 1;//
            initDay(n_year,n_month);
        }
    };
    public void mydianzan(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("accountId", myid);
        params.put("date", date);
        addSubscription(apiStores.AddPraise(params),
                new ApiCallback<ZanResult>() {

                    @Override
                    public void onSuccess(ZanResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            if(model.getData()){
                                zan++;
                                tv_zan.setText(zan+"");
                                iv_xin.setImageResource(R.mipmap.zan_t);
                                ismypress=true;
                            }else{
                                toastShow(model.getMessage());
                            }
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    public void dianzan(final String id){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("accountId", id);
        params.put("date", date);
        addSubscription(apiStores.AddPraise(params),
                new ApiCallback<ZanResult>() {

                    @Override
                    public void onSuccess(ZanResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            if(model.getData()){
                              for (int i=0;i<list.size();i++){
                                  if(list.get(i).getAccountId()==Integer.parseInt(id)){
                                      list.get(i).setPoints( list.get(i).getPoints()+1);
                                      break;
                                  }
                              }
                                paimingAdapter.setList(list);
                            }else{
                                toastShow(model.getMessage());
                            }
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
